package com.dangdang.controller;

import com.dangdang.entity.*;
import com.dangdang.service.OrderService;
import com.dangdang.service.impl.OrderServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/order")
public class OrderController {
    private OrderService os = new OrderServiceImpl();
    @RequestMapping("/insert")
    public String insert(int address_id, HttpSession session){
        User user = (User)session.getAttribute("user");
        Cart cart = (Cart)session.getAttribute("cart");
        Order order = new Order();
        order.setPrice(cart.getTotalMoney());
        order.setState(1);
        order.setAddress_id(address_id);
        order.setUser_id(user.getId());
        List<OrderItem> orderItemList = new ArrayList<>();
        Map<Integer, CartItem> buyBooks = cart.getBuyBooks();
        Set<Map.Entry<Integer, CartItem>> entries = buyBooks.entrySet();
        for(Map.Entry entry:entries){
            OrderItem orderItem = new OrderItem();
           CartItem cartItem = (CartItem)entry.getValue();
            orderItem.setProduct_id(cartItem.getBook().getId());
            orderItem.setCount(cartItem.getCount());
            orderItem.setAmount(cartItem.getCount()*cartItem.getBook().getDangPrice());
            orderItemList.add(orderItem);
        }
        order.setOrderItemList(orderItemList);
        os.insert(order);
        session.removeAttribute("cart");
        return "redirect:/order/order_ok.jsp?id="+order.getId()+"&totalMoney="+cart.getTotalMoney();
    }

    @RequestMapping("/selectMyOrder")
    public String selectMyOrder(HttpSession session, Model model){
        User user = (User)session.getAttribute("user");
        List<Order> orderList = os.selectByUid(user.getId());
        model.addAttribute("orderList",orderList);
        return "forward:/order/my_order.jsp";
    }
    @RequestMapping("/changeState")
    public String changeState(int out_trade_no){
        os.changeState(out_trade_no);
        return "redirect:/order/selectMyOrder.do";
    }
}
